package view;

import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import pojo.ChessOnlineRoom;
import util.Utils;
import widget.MyButtonWidget;
import widget.UserInfoWidget;
import callback.BackToLobbyCallback;
import callback.StartGameCallback;
import client.Client;

public class RoomView extends ChessOnlineView {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5673642782707739909L;
	private UserInfoWidget mViewPlayerA;
	private UserInfoWidget mViewPlayerB;
	private MyButtonWidget mStartBtn;
	private MyButtonWidget mBackBtn;
	
	private MouseListener mMyListener = new MouseAdapter() {
		@Override
		public void mouseClicked(MouseEvent e) {
			mStartBtn.onClick(e);
			mBackBtn.onClick(e);
			super.mouseClicked(e);
		}
	};
	
	public RoomView(Client mainScreen, ChessOnlineRoom room) {
		super(mainScreen);
		
		mStartBtn = new MyButtonWidget(320, 400, "Resources/Images/start-button-enable.png",
				"Resources/Images/start-button-disable.png", "", new StartGameCallback(mMainScreen, room));
		
		if(room.getPlayerA().getUsername().compareTo(Utils.getCurrentUser()) != 0 || room.getPlayerB() == null)
			mStartBtn.disable();// only owner can start when have 2 player
		
		mBackBtn = new MyButtonWidget(650, 450, "Resources/Images/back-icon.png", 
				"Resources/Images/back-icon.png", "", new BackToLobbyCallback(mMainScreen, room));
		
		updateRoomView(room);
		this.add(mStartBtn);
		this.add(mBackBtn);
		this.addMouseListener(mMyListener);
	}

	private void updateRoomView(ChessOnlineRoom room) {
		if(mViewPlayerA != null)
			this.remove(mViewPlayerA);
		if(room.getPlayerA() != null) {
			mViewPlayerA = new UserInfoWidget(room.getPlayerA(), 200, 100);
			this.add(mViewPlayerA);
		}
			
		if(mViewPlayerB != null)
			this.remove(mViewPlayerB);
		if(room.getPlayerB() != null) {
			mViewPlayerB = new UserInfoWidget(room.getPlayerB(), 600, 100);
			this.add(mViewPlayerB);
		}
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		if(mViewPlayerA != null)
			mViewPlayerA.paint(g);
		
		if(mViewPlayerB != null)
			mViewPlayerB.paint(g);
		
		mStartBtn.paint(g);
		mBackBtn.paint(g);
	}

}
